package com.tengju.data.domain.shared;

import lombok.Getter;

import javax.validation.constraints.NotNull;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Objects;

/**
 * @author chenhang
 * @Date 2021/3/18
 */
@Getter
public class Month {

    LocalDate startDate;
    LocalDate endDate;
    Integer monthInt;
    String monthStr;
    LocalDate randomDate;
    public static final Integer TENGJU_FIRST_MONTH = 202101;

    public Month(LocalDate randomDate) {
        if (randomDate == null) {
            return;
        }
        this.randomDate = randomDate;
        this.endDate = randomDate.with(TemporalAdjusters.lastDayOfMonth());
        this.startDate = randomDate.with(TemporalAdjusters.firstDayOfMonth());
        this.monthStr = randomDate.format(DateTimeFormatter.ofPattern("yyyy-MM"));
        this.monthInt = CastUtil.castInt(randomDate.format(DateTimeFormatter.ofPattern("yyyyMM")));
    }

    public Month(Integer monthInt) {
        this(LocalDate.parse(monthInt * 100 + 1 + "",DateTimeFormatter.ofPattern("yyyyMMdd")));
    }

    public String format(@NotNull String pattern) {
        return this.randomDate.format(DateTimeFormatter.ofPattern(pattern));
    }

    public boolean sameMonth(LocalDate date) {
        return startDate.compareTo(date) <=0 && endDate.compareTo(date) >= 0;
    }

    public Month preMonth() {
        return new Month(this.startDate.minusMonths(1));
    }

    public Month nextMonth() {
        return new Month(this.startDate.plusMonths(1));
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Month month = (Month) o;
        return Objects.equals(monthInt, month.monthInt);
    }

    /**
     * 获取本月的天数
     *
     * @return int
     */
    public int getMonthDays(){
        return Integer.parseInt(String.valueOf(this.getEndDate().toEpochDay() - this.getStartDate().toEpochDay() + 1));
    }

    @Override
    public int hashCode() {
        return Objects.hash(monthInt);
    }


}
